using UnityEngine;
using System.Collections;
using DanielSig.UnityExtensions;
using DanielSig;

public class LaserSensor : MonoBehaviour, ISensor
{
	public bool HasFixedDirection{ get{ return true; } }
	public SensationType Type{ get{ return _type; } }
	public float[] Values{ get{ return _values; } }
	
	[SerializeField]
	private SensationType _type;
	
	[SerializeField]
	private float[] _values = new float[2];
	
	public float Range = 50F;
	public float Radius = 0F;
	public LayerMask Mask;
	public Color LaserColor = Color.red;
	
	public void UpdateSensors()
	{
		Ray laser = new Ray(transform.position, transform.forward);
		RaycastHit hit = Radius > 0 ? laser.GetHit(Range, Radius, Mask.value) : laser.GetHit(Range, Mask.value);
		if(hit.collider)
		{
			_type = hit.collider.Request<SensationType>("Observation", SensationType.None);
			_values[0] = hit.distance;
		}
		else
		{
			_type = SensationType.None;
			_values[0] = Range;
		}
		_values[1] = transform.localEulerAngles.y / 180F;
	}
	void OnDrawGizmos()
	{
		Gizmos.color = LaserColor.SetAlpha(0.75F);
		Gizmos.DrawRay(transform.position, transform.forward * (_values != null && _values.Length > 0 && _values[0] != 0 ? _values[0] : Range));
	}
	void OnDrawGizmosSelected()
	{
		Gizmos.color = LaserColor;
		Vector3 pos = transform.position;
		Vector3 dir = transform.forward * (_values != null && _values.Length > 0 && _values[0] != 0 ? _values[0] : Range);
		Vector3 normal = dir.normalized * (0.01F + Radius);
		Gizmos.DrawRay(pos + normal.Up(), dir);
		Gizmos.DrawRay(pos + normal.Right(), dir);
		Gizmos.DrawRay(pos + normal.Down(), dir);
		Gizmos.DrawRay(pos + normal.Left(), dir);
	}
}

